package com.drd.dt.back.service.Impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.drd.dt.back.dao.UserManageMapper;
import com.drd.dt.back.dto.UserManageDTO;
import com.drd.dt.back.service.IUserManageService;
import com.drd.dt.common.Constant;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.modular.entity.User;
import com.drd.dt.util.CodeUtils;
import com.drd.dt.util.ResultUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by 86514 on 2019/4/10.
 */
@Transactional
@Service
public class IUserManageServiceImpl extends ServiceImpl<UserManageMapper, User> implements IUserManageService {

    @Autowired
    private UserManageMapper userManageMapper;

    /**
     * 获取用户列表
     */
    @Override
    public Tip list(UserManageDTO userManageDTO) {
        Integer offset = userManageDTO.getOffset();
        Integer pageSize = Constant.PAGE_SIZE_20;
        Integer pageNum = offset / pageSize + 1;
        Page page = new Page(pageNum, pageSize);
        List<UserManageDTO> list = userManageMapper.selectUserList(page,userManageDTO);
        list.stream().forEach(t -> {
            String introducer = t.getIntroducer();
            if (!StringUtils.isEmpty(introducer)){
                t.setIntroducer_code(CodeUtils.idToCode(introducer));
            }
        });
        page.setRecords(list);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(),page);
    }

    /**
     * 修改用户等级
     **/
    @Override
    public Tip update(Integer user_id, Integer level,String lv_expire_time,Integer status) {
        if (StringUtils.isEmpty(user_id) || StringUtils.isEmpty(level)){
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        User user = new User();
        user.setId(user_id);
        user.setLevel(level);
        if (!StringUtils.isEmpty(lv_expire_time)){
            user.setLv_expire_time(lv_expire_time);
        }
        user.setStatus(status);
        userManageMapper.updateById(user);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    /**
     * 用户详情
     **/
    @Override
    public Tip detail(Integer user_id) {
        User user = userManageMapper.selectById(user_id);
        UserManageDTO userManageDTO = new UserManageDTO();
        BeanUtils.copyProperties(user,userManageDTO);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(),userManageDTO);
    }

}
